/**
 * 
 */
package com.flute.framework;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.io.FileUtils;

import com.flute.framework.business.TimerFileData;
import com.flute.framework.configuration.FileDataPreparerXMLConverter;
import com.flute.framework.exception.ConfigurationParseException;

/**
 * @author Jazz
 * 
 */
public class FileData {
	private Map<String, TimerFileData> fileDataMap = new ConcurrentHashMap<String, TimerFileData>();
	private static FileData instance;

	private FileData() throws ConfigurationParseException, IOException {
		initial();
	}

	private void initial() throws ConfigurationParseException, IOException {
		URL url = Flute.class.getClassLoader().getResource(
				"config/preparer/filedata");
		if (url == null) {
			throw new ConfigurationParseException("找不到file data preparer配置文件.");
		}
		File file = new File(url.getPath());
		File[] files = file.listFiles();
		if (files != null) {
			for (File f : files) {
				if (f.isFile() && f.getName().endsWith(".xml")) {
					TimerFileData info = FileDataPreparerXMLConverter
							.getTimerFileDataInfo(FileUtils.openInputStream(f));
					if (info.getPreparer() != null) {
						fileDataMap.put(info.getPreparer()
								.getFilePreparerName(), info);
					}

				}
			}
		}
	}

	/**
	 * path 为file data preparer配置文件的folder所在位置
	 * 
	 * @param path
	 * @return
	 * @throws ConfigurationParseException
	 * @throws IOException
	 */
	public synchronized static FileData getInstance()
			throws ConfigurationParseException, IOException {
		if (instance == null) {
			instance = new FileData();
		}

		return instance;
	}

	public TimerFileData getTimerFileData(String name) {
		return fileDataMap.get(name);
	}

	public String[] getAllFileDatas() {
		return fileDataMap.keySet().toArray(new String[] {});
	}

	public boolean isValidFileData(String key) {
		return fileDataMap.containsKey(key);
	}

}
